#include "mainwindow.h"
#include "myorderspanel.h" // Include the new panel header
#include "orderingpanel.h"
#include <QListWidget>
#include <QStackedWidget>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QWidget>
#include <QApplication>
#include <QStyleFactory>
#include <QStyle>
#include <QFile>
#include <QTextStream>
#include <QListWidgetItem> // Include for QListWidgetItem
#include "usermanagementpanel.h" // Include the user panel header
#include "productmanagementpanel.h" // Include the product panel header
#include "ordermanagementpanel.h" // Include the order panel header

// Helper function to load QSS from file (optional, can embed directly)
QString loadStyleSheet(const QString &path) {
    QFile file(path);
    if (file.open(QFile::ReadOnly | QFile::Text)) {
        QTextStream stream(&file);
        return stream.readAll();
    }
    return "";
}

// Update constructor to accept userId
MainWindow::MainWindow(const QString& username, int userId, int userType, QWidget *parent)
    : QMainWindow(parent),
      currentUser(username),
      currentUserId(userId), // Store the user ID
      currentType(userType),
      isDarkTheme(true) // Default to dark
{
    setWindowTitle("校园咖啡订餐系统"); // Simpler title
    resize(1000, 700); // Adjust size for sidebar layout

    QWidget* central = new QWidget(this);
    setCentralWidget(central);
    central->setObjectName("centralWidget");

    // Left Navigation List
    navigationList = new QListWidget();
    navigationList->setObjectName("navigationList");
    navigationList->setFixedWidth(200); // Fixed width for sidebar
    navigationList->setCursor(Qt::PointingHandCursor);
    // 禁止获得焦点，彻底去除虚线框
    navigationList->setFocusPolicy(Qt::NoFocus);

    // Right Content Stack
    contentStack = new QStackedWidget();
    contentStack->setObjectName("contentStack");

    // Top Bar (remains similar)
    btnTheme = new QPushButton("切换主题");
    btnTheme->setObjectName("themeButton");
    btnTheme->setFixedWidth(100);
    btnTheme->setCursor(Qt::PointingHandCursor);

    QLabel* lblUser = new QLabel(QString("用户：%1").arg(username)); // Simpler user info
    lblUser->setObjectName("userInfoLabel");

    // Placeholder for Logo/Title in top-left if needed
    QLabel* lblLogo = new QLabel("🥤咖啡订餐");
    lblLogo->setObjectName("logoLabel");
    lblLogo->setStyleSheet("font-size: 16px; font-weight: bold; padding-left: 10px;"); // Basic style

    QWidget* topBarWidget = new QWidget();
    topBarWidget->setObjectName("topBar");
    QHBoxLayout* topBar = new QHBoxLayout(topBarWidget);
    topBar->addWidget(lblLogo); // Add logo/title placeholder
    topBar->addStretch();
    topBar->addWidget(lblUser);
    topBar->addWidget(btnTheme);
    topBar->setContentsMargins(0, 5, 10, 5); // Adjust margins

    // Main Layout: Horizontal split (Navigation | Content)
    QHBoxLayout* mainHLayout = new QHBoxLayout();
    mainHLayout->addWidget(navigationList);
    mainHLayout->addWidget(contentStack, 1); // Content takes remaining space
    mainHLayout->setContentsMargins(0, 0, 0, 0);
    mainHLayout->setSpacing(0);

    // Overall Layout: Top Bar + Main Horizontal Layout
    QVBoxLayout* centralLayout = new QVBoxLayout(central);
    centralLayout->addWidget(topBarWidget);
    centralLayout->addLayout(mainHLayout);
    centralLayout->setContentsMargins(0, 0, 0, 0);
    centralLayout->setSpacing(0);

    setupUI(); // Populate navigation and content stack
    applyTheme(isDarkTheme); // Apply default theme

    connect(btnTheme, &QPushButton::clicked, this, &MainWindow::onThemeSwitch);
    // Disconnect the default row change connection temporarily
    // connect(navigationList, &QListWidget::currentRowChanged, contentStack, &QStackedWidget::setCurrentIndex);
    // We'll connect itemClicked instead to handle special cases like 'My Orders'
    connect(navigationList, &QListWidget::itemClicked, this, [this](QListWidgetItem *item){
        int row = navigationList->row(item);
        if (item->text() == "📝 我的订单") {
            showMyOrders();
            // Optionally keep the selection on the 'My Orders' item
            // or switch the stack to a dedicated (possibly empty) page for it
            // For simplicity, let's just show the panel as a separate window/dialog for now.
            // If integrating into the stack, you'd need to manage adding/removing the panel widget.
        } else {
            contentStack->setCurrentIndex(row); // Normal stack switching
        }
    });
}

void MainWindow::setupUI()
{
    navigationList->clear();
    // Clear previous widgets from stack before adding new ones
    while(contentStack->count() > 0) {
        QWidget* widget = contentStack->widget(0);
        contentStack->removeWidget(widget);
        widget->deleteLater(); // Important to delete widgets properly
    }

    // Helper lambda to create simple placeholder pages
    auto createPlaceholderPage = [](const QString& text) {
        QWidget* page = new QWidget();
        QVBoxLayout* layout = new QVBoxLayout(page);
        QLabel* label = new QLabel(text);
        label->setAlignment(Qt::AlignCenter);
        layout->addWidget(label);
        return page;
    };

    if (currentType == 1) { // 管理员
        // Admin Panels
        UserManagementPanel* userPanel = new UserManagementPanel();
        navigationList->addItem("👤 用户管理");
        contentStack->addWidget(userPanel);

        // Placeholder for other admin panels
        navigationList->addItem("☕ 商品管理");
        ProductManagementPanel* productPanel = new ProductManagementPanel();
        contentStack->addWidget(productPanel);

        navigationList->addItem("📝 订单管理");
        OrderManagementPanel* orderPanel = new OrderManagementPanel();
        contentStack->addWidget(orderPanel);

        // Ensure "My Orders" item exists for admin
        bool myOrdersExists = false;
        for(int i = 0; i < navigationList->count(); ++i) {
            if(navigationList->item(i)->text() == "📝 我的订单") {
                myOrdersExists = true;
                break;
            }
        }
        if (!myOrdersExists) {
             navigationList->addItem("📝 我的订单");
        }
        // We don't add a widget to the stack; it's handled by showMyOrders

        navigationList->addItem("⚙️ 设置");
        contentStack->addWidget(createPlaceholderPage("设置界面 (开发中)"));


    } else { // 普通用户
        // Placeholder for user panels
        navigationList->addItem("☕ 订餐");
        OrderingPanel* orderingPanel = new OrderingPanel(currentUserId, this);
        contentStack->addWidget(orderingPanel);

         // Ensure "My Orders" item exists for normal user
        bool myOrdersExistsUser = false;
        for(int i = 0; i < navigationList->count(); ++i) {
            if(navigationList->item(i)->text() == "📝 我的订单") {
                myOrdersExistsUser = true;
                break;
            }
        }
        if (!myOrdersExistsUser) {
             navigationList->addItem("📝 我的订单");
        }
        // We don't add a widget to the stack; it's handled by showMyOrders

        navigationList->addItem("⚙️ 设置");
        contentStack->addWidget(createPlaceholderPage("设置界面 (开发中)"));
    }
    navigationList->setCurrentRow(0); // Select the first item by default
}

void MainWindow::applyTheme(bool dark)
{
    isDarkTheme = dark;
    QString mainQss; // Renamed to avoid confusion
    QString cardQss;
    QString combinedQss;

    // Base font for consistency
    qApp->setFont(QFont("Microsoft YaHei UI", 10)); // Example base font

    if (dark) {
        // --- Load Main Dark Theme ---
        mainQss = R"(
            QMainWindow, #centralWidget {
                background-color: #1f1f1f; /* Dark background */
            }
            #topBar {
                background-color: #2a2a2a; /* Slightly lighter top bar */
                border-bottom: 1px solid #3a3a3a;
            }
            #logoLabel {
                color: #e0e0e0;
            }
            #userInfoLabel {
                color: #b0b0b0; /* Lighter grey text */
                font-size: 12px;
                padding-right: 10px;
            }
            #themeButton {
                background-color: #3a3a3a;
                color: #e0e0e0;
                border: none;
                padding: 6px 12px;
                border-radius: 15px; /* Rounded button */
                font-size: 12px;
            }
            #themeButton:hover {
                background-color: #4a4a4a;
            }
            QListWidget#navigationList {
                background-color: #2a2a2a; /* Sidebar background */
                border: none; /* No border */
                color: #b0b0b0; /* Default text color */
                padding-top: 10px;
            }
            QListWidget#navigationList::item {
                padding: 12px 20px; /* Item padding */
                border-radius: 5px; /* Slightly rounded items */
                margin: 2px 10px; /* Margin around items */
            }
            QListWidget#navigationList::item:hover {
                background-color: #3a3a3a; /* Hover background */
            }
            QListWidget#navigationList::item:selected {
                background-color: #007acc; /* Example selection color (adjust) */
                color: #ffffff; /* Selected text color */
                font-weight: bold;
            }
            QStackedWidget#contentStack {
                background-color: #1f1f1f; /* Content area background */
            }
            /* Style for content inside stack */
            #contentStack QWidget { /* Target widgets inside the stack */
                 background-color: #1f1f1f; /* Ensure content background matches */
                 color: #e0e0e0;
            }
            #contentStack QLabel {
                 color: #e0e0e0;
                 font-size: 16px;
                 padding: 20px; /* Add padding to content labels */
            }
        )";
        // --- Load Dark Card Theme ---
        cardQss = loadStyleSheet(":/themes/dark_card.qss"); // Assuming QRC path, adjust if needed
        if (cardQss.isEmpty()) {
            qDebug() << "Warning: Could not load dark_card.qss";
            // Optionally load from file system as fallback:
            // cardQss = loadStyleSheet("themes/dark_card.qss");
        }

        btnTheme->setText("☀️亮色模式");
    } else {
        // --- Load Main Light Theme ---
        mainQss = R"(
            QMainWindow, #centralWidget {
                background-color: #ffffff; /* White background */
            }
            #topBar {
                background-color: #f9f9f9; /* Very light grey top bar */
                border-bottom: 1px solid #e9e9e9;
            }
             #logoLabel {
                color: #333333;
            }
            #userInfoLabel {
                color: #555555;
                font-size: 12px;
                 padding-right: 10px;
            }
            #themeButton {
                background-color: #e9e9e9;
                color: #333333;
                border: none;
                padding: 6px 12px;
                border-radius: 15px;
                font-size: 12px;
            }
            #themeButton:hover {
                background-color: #dcdcdc;
            }
            QListWidget#navigationList {
                background-color: #f0f0f0; /* Light sidebar background */
                border: none;
                color: #555555;
                padding-top: 10px;
            }
            QListWidget#navigationList::item {
                padding: 12px 20px;
                border-radius: 5px;
                margin: 2px 10px;
            }
            QListWidget#navigationList::item:hover {
                background-color: #e0e0e0;
            }
            QListWidget#navigationList::item:selected {
                background-color: #007acc; /* Example selection color */
                color: #ffffff;
                font-weight: bold;
            }
            QStackedWidget#contentStack {
                background-color: #ffffff;
            }
             /* Style for content inside stack */
            #contentStack QWidget {
                 background-color: #ffffff;
                 color: #333333;
            }
            #contentStack QLabel {
                 color: #333333;
                 font-size: 16px;
                 padding: 20px;
            }
        )";
        // --- Load Light Card Theme ---
        cardQss = loadStyleSheet(":/themes/light_card.qss"); // Assuming QRC path, adjust if needed
         if (cardQss.isEmpty()) {
            qDebug() << "Warning: Could not load light_card.qss";
            // Optionally load from file system as fallback:
            // cardQss = loadStyleSheet("themes/light_card.qss");
        }

        btnTheme->setText("🌙暗色模式");
    }

    // Combine and apply styles
    combinedQss = mainQss + "\n" + cardQss; // Append card styles
    qApp->setStyleSheet(combinedQss);
}

void MainWindow::onThemeSwitch()
{
    applyTheme(!isDarkTheme);
}

// Slot implementation to show the My Orders panel
void MainWindow::showMyOrders()
{
    // Option 2: Lazy load a single instance (member variable)
    if (!myOrdersPanel) {
        myOrdersPanel = new MyOrdersPanel(this); // Create only if it doesn't exist
        // Optional: Set window flags if you want it as a separate window
        // myOrdersPanel->setWindowFlags(Qt::Window);
        myOrdersPanel->setWindowTitle("我的订单 - " + currentUser);
        myOrdersPanel->resize(800, 600);
    }
    myOrdersPanel->loadOrders(currentUserId); // Load/refresh data
    myOrdersPanel->show();
    myOrdersPanel->raise(); // Bring to front if already open
    myOrdersPanel->activateWindow();
}